# -*- coding: utf-8 -*-
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from taobao_check.tools import get_browser, UserInfo, BaseSelenium, print_log


class ECommerceBrain(BaseSelenium):
    timeout = 25
    login_url = "https://www.dianshangdanao.com"
    check_url = "https://www.dianshangdanao.com/views/search/checkTool.html?checkTool=check"
    user_url = "https://www.dianshangdanao.com/views/user/user.html"
    credit_map = {"red": "心", "blue": "黄钻", "cap": "蓝冠", "crown": "黄冠"}

    def __init__(self, username: str, password: str, print_log=print_log, debug=False, no_log=False):
        """
        电商大脑的初始化函数
        Args:
            username: 用户名，一般为手机号
            password: 密码
            print_log: 打印日志的函数，必须要接受一个debug参数，debug为True时不打印
            debug: 照妖镜的debug，为True时不显示浏览器界面
            no_log: 是否初始化的时候不打印日志
        """
        super().__init__()
        self.username = username
        self.password = password
        self.print_log = print_log
        self.debug = debug
        self.init_env(no_log)

    def init_env(self, no_log=False):
        """
        初始化浏览器并登录电商大脑
        Args:
            no_log: 为True表示不打印日志
        Returns:
            None
        """
        self.env_ok = False
        self.print_log("开始登录电商大脑....", no_log)
        start = time.time()
        self.quit()
        if self.debug:
            self.browser = get_browser(headless=False, load_image=True)
        else:
            self.browser = get_browser()
        self.login()
        self.env_ok = True
        self.print_log(f"电商大脑登录成功!用时: {time.time()-start:.2f}s", no_log)

    def login(self):
        """
        电商大脑平台的登录
        Returns:
            None
        """
        # 获取两次url以消除弹框
        if self.browser.current_url != self.login_url:
            self.browser.get(self.login_url)
            self.browser.get(self.login_url)
        # 切换到账号密码登录
        account_login_button = (By.XPATH, '//*[@id="login"]/div[1]/span[2]')
        self.click_button(account_login_button)
        # 输入用户名
        self.enter_text((By.ID, "loginUsername"), self.username)
        # 输入密码
        self.enter_text((By.ID, "loginPassword"), self.password)
        # 点击登录
        self.click_button((By.ID, "loginBtn"))
        # 跳转到验号的网页
        time.sleep(1)
        self.browser.get(self.check_url)

    def check_tip_box(self):
        """
        检查是否有错误弹框
        Returns:
            有弹框则返回弹框文本信息，否则返回None
        """
        try:
            tip = WebDriverWait(self.browser, 2). \
                until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.layui-layer-content")))
            return tip.text
        except:
            return None

    def search_user(self, username):
        """
        搜索一个用户
        Args:
            username: 用户名
        Returns:
            用户信息的类，如果遇到弹窗则返回None
        """
        if self.browser.current_url != self.check_url:
            self.browser.get(self.check_url)
        # 输入用户ID
        user_entry = self.enter_text((By.ID, "checkInp"), username)
        time.sleep(1)
        # 点击查询
        user_entry.send_keys(Keys.ENTER)
        # 等待查询完成
        check_button = self.find_button((By.ID, "checkBtn"))
        while check_button.get_attribute('class') == 'searchBtn disable':
            time.sleep(0.2)
        # 处理异常弹框，目前已知的异常弹框有("请您前往个人中心登录！", "该旺旺ID不存在.请更改", "旺旺号不可为空！", "提交长度非法，旺旺为2-25位，请重新提交！")
        tip = self.check_tip_box()
        if tip:
            if tip == "请您前往个人中心登录！":
                self.login()
                return self.search_user(username)
            else:
                self.browser.get(self.check_url)
                return None
        else:
            return self.parse_result(username)

    def parse_result(self, username):
        """解析查询页面中的数据"""
        user = UserInfo(username)
        user_info = self.find_element((By.ID, "checkInfo"))
        tds = user_info.find_elements_by_tag_name("td")
        # 获取买家信誉
        try:
            img = tds[1].find_element_by_tag_name("img").get_attribute('src')
            img = img.split(".")[2].split("_")
            user.credit_type = self.credit_map[img[1]]
            user.credit_level = int(img[-1])
        except:
            pass
        # 查看买家是否超级会员
        try:
            svip = tds[9].find_element_by_tag_name("img").get_attribute('src')
            user.svip = (svip != "https://file.sdjr.online/201908061151103698.png")
        except:
            user.svip = False

        # 获取买家周平均
        user.week_avg = float(tds[4].find_element_by_tag_name("span").text)

        buy_record = self.find_element((By.ID, "buy"))
        # 获取买家日平均
        try:
            buy_record.find_element_by_tag_name("span")
        except:
            pass
        else:
            buy_rows = buy_record.find_elements_by_tag_name("tr")
            for row in buy_rows:
                day = row.find_elements_by_tag_name("span")[-1].get_attribute('textContent')
                user.day_avg.append(float(day))

        # 查询打标记录
        mark_info = self.find_element((By.ID, "mark"))
        tds = mark_info.find_elements_by_tag_name("td")
        # user.fox = int(tds[0].find_element_by_id("fox").text)
        user.downright = int(tds[1].find_element_by_id("jiangNum").text)
        # user.blacklist = int(tds[2].find_element_by_id("yunBlack").text)
        # 本周查询人数
        user.near_week_check = int(self.browser.find_element_by_id("weekCount").text)
        # 上周查询人数
        user.last_week_check = int(self.browser.find_element_by_id("countBefore").text)

        return user

    def check(self, user: UserInfo) -> bool:
        if user is None:
            return False

        if user.downright > 0:
            return False

        if user.credit_type == "心" and user.credit_level < 4:
            return False

        if user.week_avg >= 2.2:
            return False

        if len(user.day_avg) > 0:
            for day in user.day_avg:
                if day > 4:
                    return False
            one = [day for day in user.day_avg if day <= 1]
            if len(one) == 0:
                return False

        if user.svip:
            if user.near_week_check > 7:
                return False
            if user.last_week_check > 7:
                return False
        else:
            if user.near_week_check > 6:
                return False
            if user.last_week_check > 6:
                return False

        return True

    def quit(self):
        try:
            self.browser.quit()
        except:
            pass


if __name__ == "__main__":
    from random import choice
    eb = ECommerceBrain("18259971977", "ancheng123", debug=True)
    print("搜索")
    names = ['tb291924592', 'qwert墨颜墨颜', 'qw4u7ac094', 'tb139619860', '幻莲晓', '如今购买力', '心缘坊服饰8', '王硕明222', '打败小s', '黄启芽','13473127800song', 'tb36471219', '不爱我717', 'tb339763558', '黄金万两1014', 'fabrecaca', 'tb028540227', '阶蒙不才子', '你好先生好你', 'alicefushiwood', 'cbu-qhjy988', 'kvxtny38713', 't_1486254809199_012', 'tb8176611_2011', '南宇汽车装饰店', '扈心75202', '陶德723', 'tb035204148', 'liruijia775', '胡滔专属', 'lm30920', 'tb870052376', '金城电动', '我是怡君唷', 'jim1242012', '2020岁岁常相见', 'mlq1021750506', 'bjai21', 'songxh8898', 'caozhenghui2013', '越努力越幸福z', 'nununa2009', 'longfei714abc', '一心一意8057', '浮生v妄言', '洪罩瞧', 'd997093730', '岁月不等人629', '王光军9032', 'aa337244017', '新城蓝色妖姬', '依储晓沁cand', 'tb089741878', 'yujiang110', 'tb367292645', 'tb_8896893', 'tb367604123', 'ljmxrx', 'ossianhowley', '亲亲宝贝吧588', 'jay8819129', '我的心都碎了74', '没齿难忘142', 'cbu-jedsir', '徐y悦qh', '史美芳881121', 'jasfish37', '低调de繁华0', '飞来的橘', 'a8x8gy9t18u6', 'wengsh666', 'cbu-xiongjie0103', '大洋冰鸽233', 'feimengcat', 'joanwang_5', '邓显这140390', 'rizdavid', '快乐兰瑟', 'tb434332593', '颖关友102929', '爱你菲宝哟', '幸福味道1213', 'tb424975077', '郑双定', 'aoxinghuojia', '子轩奕涵', '陌上人如玉841110', '哭泣的秋天', 'tb616420273', '生活继续中任悦', '饶江河', '小可爱曼祎', '柠凉初夏', 'yang750415', '年少怎么能不猖狂', 'cm54321_2009', '小林林1990318', 'jindai', 'yoyo125811', '阿珏少爷', 'tb0219175025', 'vc海贼王', 'tb612250484', 'hpqingfeng2009', '排圩6队', 'cbu-zhaohuixinyuan', 'mp249553', '黑色嗨客', 'yanbolu1996', 'tb342739016', 'tb2565725863', '云上の天空', '江国春88', '叮叮咚19903', 'tb128248233', '茵茵春天', '花开花谢8494', 'tb3684074767', 'koala2230', '紫凝2335', '兰宝贝2008', '爱莫霖琳', '香香榴莲1985', '肌拇本闭', '冰凌花63682', '啊707547006', '晁梵紫菀苏', '我行我素1296', 'xiajiani', '小石520475', 'tmd303', '万事xc如意', '一根天使的羽毛糖', '冰是睡着的水18769371', 'bsing007', 'tb453703445', '神界仙灵', 'chenqindian', 't_1513508324099_0734', '早早交货了', 't_1488724323167_0901', '靖宝爱你1988', '平平安安0409', '回忆里模糊的样子', 'basaby', 'lioiioil', 'maxiaoting2010', 'us敏林308', '我只会黄哈哈', 'qq710983318', 'tb35957209', 'tb86733101', '有扇子', '倾城倾城99', 'muziyuepengpeng', 'tb67050375', '费飞飞520', 'tb4891125391', 'kxdd99', '兜兜里面有糖丶', '香巷子宽', 'qinqingdenglu9', '吴晓华1314520', '度果到一边', '1218丹', 'tb77032913', 'tb437455754', '陈姗云', '残梦照祠堂', 'lgx10001388', 'luolijun13878367735', '柠檬脾气83204513', '奥黛丽赫本zara', '芹菜萝卜我都爱', 'yujuang回忆童年', '564841200qqcom', 'dodolook27', 'j4564466', 't_1491813559180_015', '痪庇汕', 'tb04650736', '亦凝桃', '管扯佑仍释', 'a79719972', '凄美的暧昧', 'gourry3661', 'liyonglin88', 'boey_777', '阿巴阿巴咔咔', 't_1511101867437_0928', '雨点的故事88', 'tb7308246561', '二丫994', '季佳婕', 'tb4483457123', 'madqxf76', 'aiyanlove1314', 'tb53207802', '飞花飞叶88', 'tongrachel']
    start = time.time()
    result = eb.search_user(choice(names))
    print(f"time: {time.time() - start}")
    print(result)
    eb.quit()
